package com.hliu.web.controller.login;

import com.hliu.shiro.model.User;
import com.hliu.shiro.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * author: 6
 * date: 13-4-18
 */
@Controller
@RequestMapping()
public class LoginController {
	Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private IUserService iUserService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login/login";
	}

	@RequiresGuest
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "login/register";
	}

	@RequestMapping(value = "/login-submit", method = RequestMethod.POST)
	public String loginSubmit(String username,String password,boolean rememberMe) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		token.setRememberMe(rememberMe);
		try {
			if(currentUser.isAuthenticated()){
				currentUser.logout();
			}
			currentUser.login(token);
		} catch (UnknownAccountException uae) {
			logger.debug(token.getUsername()+",{}", uae.getMessage());
		} catch (IncorrectCredentialsException ice) {
			logger.debug(token.getPassword()+",{}", ice.getMessage());
		} catch (AuthenticationException ae) {
			logger.debug("用户名密码错误, {}", ae.getMessage());
		}
		return "redirect:/index";
	}

	@RequestMapping(value = "/register-submit", method = RequestMethod.POST)
	public String registerSubmit(String username,String password) {
		User user = new User();
		PasswordService svc = new DefaultPasswordService();
		String encrypted = svc.encryptPassword(password);
		user.setUsername(username);
		user.setPassword(encrypted);
		iUserService.save(user);
		return "redirect:/login";
	}

	@RequestMapping(value = "/logout",method = RequestMethod.GET)
	public String logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login";
	}


}
